const Schema = require('validate')
const { ValidationError, UnknownError } = require('../utils/errors')
const fs = require('fs')
const {
  addMessageDao,
  findMessageByPageDao,
  deleteMessageDao,
  findDayNumOfMessageDao,
  findMessageByIdDao,
  findBlogsCommentByPageDao,
  delBlogsCommentDao,
  delReplyComentDao,
} = require('../dao/messageDao')
const { findBlogByIdDao,updateBlogComNumberAdmNoComNoDao, } = require('../dao/blogDao')
const { formatResponse, handleDataPattern, getMidnightTimestamp } = require('../utils/tool')
const { uFilterSenWords } = require('../utils/uFilterSensitiveWords')
const dir = './public/static/avatar'

/**
 * 读取一个目录下有多少个文件
 * @param {*} dir 目录地址
 */
async function readDirLength(dir) {
  return new Promise((resolve) => {
    fs.readdir(dir, (err, files) => {
      if (err) throw new UnknownError()
      resolve(files)
    })
  })
}

// 新增评论或者留言
module.exports.addMessageService = async function (newMessage) {
  // 数据验证规则
  const messageRule = new Schema({
    nickname: {
      required: true,
      type: String,
    },
    content: {
      required: true,
      type: String,
    },
    ip: {
      required: true,
      type: String,
    },
    blogId: {
      required: false,
      type: String,
    },
  })
  //留言条数限制
  // 进行数据验证
  const validateResult = messageRule.validate(newMessage)
  if (validateResult.length == 0) {
    newMessage.blogId = newMessage.blogId ? newMessage.blogId : null
    newMessage.createDate = Date.now()
    // 有一个头像的地址，该头像是随机生成的
    // 读取 static 下面的 avatar 目录
    const files = await readDirLength(dir)
    // 随机摇一个文件出来
    const randomIndex = Math.floor(Math.random() * files.length)
    newMessage.avatar = '/static/avatar/' + files[randomIndex]
    //敏感词过滤
    try {
      newMessage.content = await uFilterSenWords(newMessage.content)
    } catch (e) {
      throw new ValidationError('敏感词过滤失败')
    }
    // 接下来开始新增
    const data = await addMessageDao(newMessage)
    // 如果是文章的评论，那么对应文章的评论数量也要自增
    if (newMessage.blogId) {
      const blogData = await findBlogByIdDao(newMessage.blogId)
      blogData.commentNumber++
      await blogData.save()
    }
    return formatResponse(0, '留言成功', data)
  } else {
    throw new ValidationError('message数据验证失败')
  }
}

// 分页获取评论或取留言
module.exports.findMessageByPageService = async function (pageInfo) {
  const data = await findMessageByPageDao(pageInfo)
  const rows = handleDataPattern(data.rows)
  return formatResponse(0, '分页获取成功', {
    total: data.total,
    rows: rows,
  })
}

// 删除留言或者评论
module.exports.deleteMessageService = async function (id) {
  const messageInfo = await findMessageByIdDao(id)
  if (messageInfo.blogId) {
    const blogInfo = await findBlogByIdDao(messageInfo.blogId)
    blogInfo.commentNumber--
    await blogInfo.save()
  }
  await deleteMessageDao(id)
  return formatResponse(0, '删除成功', true)
}

// 查询当日的留言数量
module.exports.findDayNumOfMessageService = async function (ip) {
  //获取当天零点的时间戳，例如现在是2024-03-10 15:17:00，那么返回的是2024-03-10 00:00:00的时间戳
  const data = await findDayNumOfMessageDao(ip, getMidnightTimestamp())
  return data
}
//分页获取博客楼层留了言
module.exports.findBlogsCommentByPageService = async function (pageInfo) {
  const data = await findBlogsCommentByPageDao(pageInfo)
  const rows = data.rows
  return formatResponse(0, '分页获取成功', {
    total: data.total,
    rows
  })
}
//删除博客楼层留言,同时删除该楼层下的评论，更新文章评论数和管理员未回复的评论数TODO:
module.exports.delBlogsCommentService = async function(data){
  console.log(`output->data`,data)
  // 删除博客楼层留言
  await delBlogsCommentDao(data)
  //删除该楼层留言下的评论
  await delReplyComentDao(data)
  //更新文章评论数和管理员未回复的评论数
  await updateBlogComNumberAdmNoComNoDao(data)
  return formatResponse(0, '删除成功', true)

}
